﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PessModel;
using System.IO;
using System.Web.Security;
using System.Reflection;
using DynamicQueryLib;
using LinqKit;
using PessMvc.Models;
using System.Diagnostics;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Text;
using DoddleReport;
using DoddleReport.Web;
using System.Collections;
using System.Globalization;
using System.Resources;
using System.Web.Profile;
using PessMvc.Helpers;
using LinqToExcel;
using LinqToExcel.Domain;
using PessMvc.Lib;
using Ionic.Zip;
using System.Data.Entity.Validation;
using System.Web.Script.Serialization;

namespace PessMvc.Controllers
{
    public class AttachmentController : Controller
    {
        private PESSEntities db;

        public AttachmentController()
        {
            db = new PESSEntities();
        }
        
        [HttpPost]
        public string Upload(HttpPostedFileBase fileData, int archiveID)
        {

            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Form["authCookie"]);
            if (ticket != null)
            {
                var identity = new FormsIdentity(ticket);
                if (!identity.IsAuthenticated)
                {
                    return "Not Authenticated";
                }
            }
            
            //if(!User.Identity.IsAuthenticated)
            //{
            //    return "Not a authorized action!";
            //}

            //var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(file.FileName));
            //file.SaveAs(fileName);

            int? activityID = db.Archives.Find(archiveID).Subject.ActivityID;

            // Verify that the user selected a file
            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(fileData.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/Archives/"), activityID.ToString(), archiveID.ToString());
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //fileData.SaveAs(Path.Combine(path, fileName));
                //Add attachment info to db.
                Archive archive = db.Archives.Find(archiveID);

                //the following lines are for AECT2005
                if (archive.Status == 4 && archive.PaperStatus >= 6)
                    fileName = archive.CalculatedSerialNumber + "_Paper_Final" + Path.GetExtension(fileData.FileName);
                else
                    fileName = archive.CalculatedSerialNumber + "_Paper_Attemp" + Path.GetExtension(fileData.FileName);

                fileData.SaveAs(Path.Combine(path, fileName));

                //1 file version
                archive.Attachments.Clear();
                FileInfo fileInfo = new FileInfo(Path.Combine(path, fileName));
                archive.Attachments.Add(new Attachment { Title = fileName, ArchiveID = archiveID, FilePath = path, TimeStamp = fileInfo.CreationTime, FileSize = (int)(fileInfo.Length / 1024) });

                //2 files version
                //Attachment doesn't exist.
                /*if (archive.Attachments.Where(a => a.Title == fileName).Count() <= 0)
                {
                    FileInfo fileInfo = new FileInfo(Path.Combine(path, fileName));
                    archive.Attachments.Add(new Attachment { Title = fileName, ArchiveID = archiveID, FilePath = path, TimeStamp = fileInfo.CreationTime, FileSize = (int)(fileInfo.Length / 1024) });
                }
                else
                {//Attachment exits.
                    Attachment attachment = archive.Attachments.Where(a => a.Title == fileName).SingleOrDefault();
                    FileInfo fileInfo = new FileInfo(Path.Combine(path, fileName));
                    attachment.FileSize = (int)(fileInfo.Length / 1024);
                    attachment.TimeStamp = fileInfo.LastWriteTime;
                    db.Entry(attachment).State = EntityState.Modified;
                }*/

                if (archive.PaperStatus < 2)
                    archive.PaperStatus = (int)ArchivePaperStatus.Submitted;
                db.Entry(archive).State = EntityState.Modified;
                db.SaveChanges();

                //send email
                using (StreamReader reader = new StreamReader(Server.MapPath("~/App_Data/templates/paperconfirm.txt")))
                {
                    string text = reader.ReadToEnd();
                    text = text.Replace("[Author]", archive.Name);
                    text = text.Replace("[Title]", archive.ProjectTitle);
                    text = text.Replace("[Date]", DateTime.Now.Date.ToString("MM/dd/yyyy"));
                    // text=text.Replace("[Authors]",);
                    // text=text.Replace("[Topic]",);
                    Utility.SendMail("Proceedings Paper Confirmation", text, archive.EMail);
                }
            }

            return "ok";
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
